package dao

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"yun_image/entity"
)

// GetUserByAccountByPassword GetUserByAccount 如果查询出错则返回err
// 如果没有查询到结果则不返回err，而是返回nil，传入的指针参数为零值
func GetUserByAccountByPassword(user *entity.User, account string, password string) error {
	result := DB.Where("account = ? and password = ?", account, password).Take(user)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) || result.Error == nil {
		return nil
	}
	return result.Error
}

func GetUserByAccount(user *entity.User, account string) error {
	result := DB.Where("account = ?", account).Take(user)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) || result.Error == nil {
		return nil
	}
	return result.Error
}

func CreateUser(user *entity.User) error {
	result := DB.Create(user)
	return result.Error
}

func UpdateUser(user *entity.User) error {
	result := DB.Save(user)
	return result.Error
}

func AddImgNumber(account string, count int) error {
	var user entity.User
	sql := fmt.Sprintf("UPDATE `%s` SET `number` = `number` + ? WHERE `account` = ?", user.TableName())
	result := DB.Exec(sql, count, account)
	return result.Error
}
